package org.xiaom.butler.controller.app;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.FileHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xiaom.butler.bean.Content;
import org.xiaom.butler.bean.app.AppVersion;
import org.xiaom.butler.service.BaseService;
import org.xiaom.butler.util.Standard;
import org.xiaom.butler.util.Util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

public class AppVersionServlet extends HttpServlet {
	BaseService appVersionService = new BaseService(AppVersion.class);
	final String field="app/version";
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String url = request.getRequestURI();
		String function = url.split("\\.")[1];
		String name = url.split("/" + field + "/")[1];
		if (function.equals("do")) { // 请求是个功能性请求
			if ("add.do".equals(name)) {
				add(request, response); 
				goToList(request, response, Standard.REDIRECT);
			} else if("edit.do".equalsIgnoreCase(name)){
				
			} else if("delete.do".equalsIgnoreCase(name)){
				delete(request, response);
				goToList(request, response,Standard.REDIRECT);
			} else {
				request.setAttribute("error_message", "没找到该页面");
				response.sendRedirect("../error.jsp");
			}
		} else if (function.equals("jsp")) {// 要求显示页面
			if (name.equals("add.jsp")) {
				goToAdd(request, response); 
			} else if ("list.jsp".equalsIgnoreCase(name)){
				goToList(request, response, Standard.FORWARD);
			} else if ("download.jsp".equalsIgnoreCase(name)){
				download(request, response, Standard.FORWARD);
			} else if ("current.jsp".equals(name)){
				current(request,response);
			}
		}
	}

	private void delete(HttpServletRequest request, HttpServletResponse response) {
		JsonObject jo=new JsonObject();
		try {
			String id = (String) request.getParameter("id");
			AppVersion v=(AppVersion) appVersionService.get(id);
			appVersionService.delete(Integer.parseInt(id));
			Util.deleteFile(v.getPath());
			
			jo.addProperty("state", "success");
			response.getWriter().write(jo.toString());
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.getWriter().write("{state:faild}");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		
	}

	private void current(HttpServletRequest request,
			HttpServletResponse response) {
		AppVersion v=getCurrent(Util.getQueryParam(request, "platform", AppVersion.PLATFORM_ANDROID));
		String rs=new GsonBuilder().create().toJson(v);
		try {
			response.getWriter().print(rs);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void download(HttpServletRequest request,
			HttpServletResponse response, boolean forward) {
		String id=Util.getQueryParam(request, "id", "");
		AppVersion v=null;
		if(Util.isBlank(id)){
			v=getCurrent(AppVersion.PLATFORM_ANDROID);
		}else{
			v=(AppVersion) appVersionService.get(Integer.parseInt(id)); 
		}
		String suffix=AppVersion.PLATFORM_ANDROID.equalsIgnoreCase(v.getPlatform())?".apk":"";
		try {
			Util.downLoad(request, response,getServletContext().getRealPath("/")+ v.getPath(), "HotelButler_v"+v.getVersion()+suffix);
		} catch (IOException e) {
			e.printStackTrace();
			try {
				response.getWriter().println("下载失败");
			} catch (IOException e1) {
			}
		}
	}

	private AppVersion getCurrent(String platform) {
		AppVersion v=(AppVersion) appVersionService.getList("from AppVersion v where v.platform='"+platform+"' order by startDate desc").get(0);
		return v;
	}

	private void goToAdd(HttpServletRequest request,
			HttpServletResponse response) {
		String platform=Util.getQueryParam(request, "platform",AppVersion.PLATFORM_ANDROID);
		request.setAttribute("platform", platform);
		Util.forward(getServletConfig().getServletContext(), request, response,
				field+"/add.jsp", false);
	}

	private void goToList(HttpServletRequest request,HttpServletResponse response, boolean mode)
			throws ServletException, IOException {  
		String hql="from AppVersion v where v.platform='"+AppVersion.PLATFORM_ANDROID+"' order by v.startDate desc";
		List<AppVersion> list=appVersionService.getList(hql);
		request.setAttribute("list", list);
		request.setAttribute("platform", "android");
		String relativePath = "/list.jsp?platform=android";
		if (Standard.FORWARD == mode) {
			Util.forward(getServletConfig().getServletContext(), request,response, field+relativePath, false);
		} else {
			Util.redirect(request, response, "list.jsp?platform=android",false);
		}
	}

	private void add(HttpServletRequest request, HttpServletResponse response) {
		String describe=Util.getQueryParam(request, "describe", "");
		String path=Util.getQueryParam(request, "path", "");
		String platform=Util.getQueryParam(request, "platform", "");
		String remark=Util.getQueryParam(request, "remark", "");
		String version=Util.getQueryParam(request, "version", "");
		Date startDate=new Date(System.currentTimeMillis());
		
		AppVersion v=new AppVersion();
		v.setDescribe(describe);
		v.setPath(path);
		v.setPlatform(platform);
		v.setRemark(remark);
		v.setStartDate(startDate);
		v.setVersion(version);
		
		appVersionService.saveOrUpdate(v);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
}
